package cn.tedu.hm.security;

import cn.tedu.hm.mapper.AdminMapper;
import cn.tedu.hm.pojo.vo.AdminLoginInfoVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 说明:
 *
 * @ author: WeiZhen
 * @date: 2023/3/6
 **/
@Service
@Slf4j
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    AdminMapper adminMapper;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        log.debug("Spring Security调用了loadUserByUsername()方法，参数：{}", s);
        AdminLoginInfoVO loginInfoByUsername = adminMapper.getLoginInfoByUsername(s);
        log.debug("从数据库中根据用户名【{}】查询登录信息，结果：{}", s, loginInfoByUsername);

        if (loginInfoByUsername == null) {
            return null;
        }
        List<GrantedAuthority> authorities = new ArrayList<>();
        List<String> permissions = loginInfoByUsername.getPermissions();
        for (String permission : permissions) {
            authorities.add(new SimpleGrantedAuthority(permission));
        }

        cn.tedu.hm.security.AdminDetails adminDetails = new cn.tedu.hm.security.AdminDetails(
                loginInfoByUsername.getId(),
                loginInfoByUsername.getUsername(),
                loginInfoByUsername.getPassword(),
                loginInfoByUsername.getEnable()==1,
                authorities
        );

        return adminDetails;
    }
}
